<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <!-- 主表单区域 -->
      <j-form-container :disabled="formDisabled">
        <a-form :form="form" slot="detail">
          <a-row>
            <a-col :xs="24" :sm="12">
              <a-form-item label="仓库" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-popup
                  v-decorator="['storeId', validatorRules.storeId]"
                  :trigger-change="true"
                  :list-data.sync="listData"
                  org-fields="id,store_name"
                  dest-fields="storeId_dictText,storeId"
                  code="store_info"
                  @callback="storeCallback"
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="12">
              <a-form-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-popup
                  v-decorator="['supplierId', validatorRules.supplierId]"
                  :trigger-change="true"
                  org-fields="id,supplier_name"
                  dest-fields="supplierId_dictText,supplierId"
                  code="supplier_info"
                  @callback="supplierCallback"
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="12">
              <a-form-item label="采购员" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-popup
                  v-decorator="['applicant', validatorRules.applicant]"
                  :trigger-change="true"
                  org-fields="id,realname"
                  dest-fields="realname,applicant"
                  code="buyer_info"
                  @callback="applicantCallback"
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="12">
              <a-form-item label="总价" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input-number :disabled="true" :precision="4" v-decorator="['totalPrice']" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="12">
              <a-form-item label="账期" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input-number
                  :max="10000"
                  :min="0"
                  :formatter="(value) => `${Math.floor(value) || 0} 天`"
                  :parser="(value) => value.replace(' 天', '')"
                  v-decorator="['paymentDay', validatorRules.paymentDay]"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="12" v-show="model.status===1">
              <a-form-item label="最后结账日" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-decorator="['finalAccountDay']" :disabled="true" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="12" v-show="model.status===1">
              <a-form-item label="结账状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-decorator="['checkoutStatus_dictText']" :disabled="true" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="12" v-show="model.status===1&&model.checkoutStatus===1">
              <a-form-item label="结账日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-decorator="['checkoutTime']" :disabled="true" style="width: 100%" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </j-form-container>

      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey" @change="handleChangeTabs">
        <a-tab-pane tab="入库审批明细表" :key="refKeys[0]" :forceRender="true">
          <j-editable-table
            :disabled="formDisabled"
            :ref="refKeys[0]"
            :loading="storeApprovalDetailTable.loading"
            :columns="storeApprovalDetailTable.columns"
            :dataSource="storeApprovalDetailTable.dataSource"
            :maxHeight="300"
            :rowNumber="true"
            :rowSelection="!formDisabled"
            :actionButton="!formDisabled"
            @added="rowAdd"
            @deleted="rowDeleted"
          >
            <template #goodsSpecificationSlot="slotProps">
              <a-select
                :disabled="formDisabled"
                v-model="goodsIdObj[slotProps.rowId].goodsSpecification"
                @change="goodsSkuChange(slotProps, $event)"
                style="width: 100%"
              >
                <a-select-option :value="item.id" v-for="(item, index) in goodsSkuData[slotProps.rowId]" :key="index">
                  {{ item.specsValues }}
                </a-select-option>
              </a-select>
            </template>

            <template #unitIdDictTextSlot="slotProps">
              <span :style="{ color: goodsIdObj[slotProps.rowId].isFales == '未设置' ? 'red' : '#000000A6' }">{{
                goodsIdObj[slotProps.rowId].isFales
              }}</span>
            </template>

            <template #storeUnitsSlot="slotProps">
              <a-select
                :disabled="formDisabled"
                v-model="goodsIdObj[slotProps.rowId].unitId"
                @change="storeUnitsChange(slotProps, $event)"
                style="width: 100%"
              >
                <a-select-option :value="item.id" v-for="(item, index) in storeUnitsData[slotProps.rowId]" :key="index">
                  {{ item.unitRelationText }}
                </a-select-option>
              </a-select>
            </template>
          </j-editable-table>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
    <template slot="footer">
      <div v-if="title == '审批'">
        <a-button key="back" @click="handleApp(2)">驳回</a-button>
        <a-button key="submit" type="primary" @click="handleApp(1)">通过</a-button>
      </div>
      <div v-if="title == '结账'">
        <a-button key="back" @click="handleCancel">关闭</a-button>
        <a-button key="submit" type="primary" @click="handleCheckout">结账</a-button>
      </div>
      <div v-if="title == '详情'">
        <a-button key="back" @click="handleCancel">关闭</a-button>
      </div>
      <div v-if="!formDisabled">
        <a-button key="back" @click="handleCancel">关闭</a-button>
        <a-button key="submit" type="primary" @click="handleOk" :disabled="istrue">确定</a-button>
      </div>
    </template>
  </j-modal>
</template>

<script>
import pick from 'lodash.pick'
import { FormTypes, getRefPromise } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { validateDuplicateValue } from '@/utils/util'
import JDate from '@/components/jeecg/JDate'
import {
  postPurchaseApproval,
  getQuerySpecsNameByGoodsIdC,
  getStockPosition,
  postCloseAccounts,
} from '@/api/storeApproval'

export default {
  name: 'StoreApprovalModal',
  mixins: [JEditableTableMixin],
  components: {
    JDate,
  },
  computed: {
    formDisabled() {
      return this.disableSubmit
    },
    istrue() {
      let arr1 = []
      let arr = Object.keys(this.goodsIdObj)
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i]
        arr1.push(this.goodsIdObj[item].isFales)
      }
      return arr1.indexOf('未设置') > -1 ? true : false
    },
  },
  watch: {
    goodsIdObj: {
      deep: true,
      immediate: true,
      handler(val) {
        let allValue = 0
        let arr = Object.keys(val)
        if (arr.length > 0) {
          arr.forEach((item) => {
            allValue += +val[item].totalPrice
          })
          this.$nextTick(() => {
            this.form.setFieldsValue({ totalPrice: allValue.toFixed(4) })
          })
        }
      },
    },
    listData: {
      immediate: true,
      handler: function (val) {
        if (val) {
          this.storeCallback({
            storeId: val[0].store_name,
            storeId_dictText: val[0].id,
          })
        }
      },
    },
  },
  data() {
    return {
      approvalId: '',
      storeFormObj: null,
      supplierFormObj: null,
      applicantFormObj: null,
      goodsSkuList: null,
      goodsSkuData: {},
      storeUnitsData: {},
      goodsIdObj: {},
      disableSubmit: false,
      listData: null,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 0,
      validatorRules: {
        storeId: {
          rules: [{ required: true, message: '请输入仓库!' }, { validator: this.storeIdChange }],
        },
        supplierId: {
          rules: [{ required: true, message: '请输入供应商!' }],
        },
        applicant: {
          rules: [{ required: true, message: '请输入采购员!' }],
        },
        paymentDay: {
          rules: [{ required: true, message: '请输入账期!' }],
        },
      },
      refKeys: ['storeApprovalDetail'],
      tableKeys: ['storeApprovalDetail'],
      activeKey: 'storeApprovalDetail',
      // 入库审批明细表
      storeApprovalDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '商品',
            key: 'goodsId',
            type: FormTypes.sel_search,
            dictCode: 'biz_goods,name,id',
            width: '200px',
            validateRules: [
              {
                required: true,
                message: '${title}不能为空',
                handler: this.goodsIdChange,
              },
            ],
          },
          {
            title: '规格',
            key: 'goodsSpecification',
            type: FormTypes.slot,
            width: '200px',
            slotName: 'goodsSpecificationSlot',
          },
          {
            title: '入库数量',
            key: 'storeNum',
            type: FormTypes.inputNumber,
            width: '200px',
            validateRules: [{ required: true, message: '${title}不能为空', handler: this.storeNumChange }],
          },
          {
            title: '入库单位',
            key: 'storeUnits',
            type: FormTypes.slot,
            width: '200px',
            slotName: 'storeUnitsSlot',
          },
          {
            title: '库存单位',
            key: 'unitId_dictText',
            type: FormTypes.slot,
            width: '100px',
            slotName: 'unitIdDictTextSlot',
          },

          {
            title: '库位',
            key: 'spaceId',
            type: FormTypes.sel_search,
            // dictCode: 'biz_store_space,space_code,id',
            options: [],
            width: '200px',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '商品总价',
            key: 'totalPrice',
            type: FormTypes.inputNumber,
            width: '200px',
            validateRules: [{ required: true, message: '${title}不能为空', handler: this.totalPriceChange }],
          },
        ],
      },
      url: {
        add: '/storage/storeApproval/add',
        edit: '/storage/storeApproval/edit',
        storeApprovalDetail: {
          list: '/storage/storeApproval/queryStoreApprovalDetailByMainId',
        },
      },
    }
  },
  methods: {
    // 审批
    handleApp(val) {
      this.confirmLoading = true
      postPurchaseApproval({ status: val, id: this.approvalId })
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
          this.$emit('ok')
          this.close()
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    // 结账
    handleCheckout() {
      this.confirmLoading = true
      let { status, checkoutStatus, id } = this.model
      postCloseAccounts({ id, status, checkoutStatus })
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
          this.$emit('ok')
          this.close()
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    storeUnitsChange(props, value) {
      let arr = Object.keys(this.goodsIdObj)
      if (arr.length) {
        arr.forEach((item) => {
          if (item == props.rowId) {
            this.$set(this.goodsIdObj[item], 'unitId', value)
            this.storeUnitsData[item].forEach((ite, ind) => {
              if (ite.id == value) {
                this.$set(this.goodsIdObj[item], 'unitRelation', ite.unitRelation)
              }
            })
          }
        })
      }
    },
    // 库存单价
    // storePriceChange(type, value, row, column, callback, target) {
    //   if (type == 'blur') {
    //     let b = 0,
    //       a = Math.abs(value).toFixed(2)
    //     let arr = Object.keys(this.goodsIdObj)
    //     arr.forEach((item) => {
    //       if (item == row.id) {
    //         b = this.goodsIdObj[item].storeNum
    //         this.$set(this.goodsIdObj[item], 'storePrice', a)
    //       }
    //     })
    //     target.setValues([
    //       {
    //         rowKey: row.id, // 行的id
    //         values: {
    //           totalPrice: (a * b).toFixed(2),
    //           storePrice: a,
    //         },
    //       },
    //     ])
    //   }
    //   callback()
    // },
    // 库存数量
    storeNumChange(type, value, row, column, callback, target) {
      if (type == 'change') {
        let a = value.toFixed(4)
        let arr = Object.keys(this.goodsIdObj)
        arr.forEach((item) => {
          if (item == row.id) {
            this.$set(this.goodsIdObj[item], 'storeNum', a)
          }
        })
        target.setValues([
          {
            rowKey: row.id, // 行的id
            values: {
              storeNum: a,
            },
          },
        ])
      }
      callback()
    },
    // 总价
    totalPriceChange(type, value, row, column, callback, target) {
      if (type == 'blur') {
        let a = value.toFixed(4)
        let arr = Object.keys(this.goodsIdObj)
        arr.forEach((item) => {
          if (item == row.id) {
            this.$set(this.goodsIdObj[item], 'totalPrice', a)
          }
        })
        target.setValues([
          {
            rowKey: row.id, // 行的id
            values: {
              totalPrice: a,
            },
          },
        ])
      }
      callback()
    },
    // 子表行添加删除修改
    rowAdd({ row, target }) {
      this.$set(this.goodsIdObj, row.id, {
        goodsId: '',
        rowKey: row.id,
        unitId: '',
        unitRelation: '',
        totalPrice: 0,
        isFales: '未设置',
      })
      let arr = Object.keys(this.goodsIdObj)
      this.setGoodsSku(arr)
    },
    rowDeleted(rowDeletedArr) {
      rowDeletedArr.forEach((item) => {
        this.$delete(this.goodsIdObj, item)
        this.$delete(this.goodsSkuData, item)
        this.$delete(this.storeUnitsData, item)
      })
    },
    // 点击时初始化下拉列表
    // goodsSkuFocus(slotProps) {
    // let g = this.goodsSkuData
    // let keys = Object.keys(g)
    // for (let i = 0; i < keys.length; i++) {
    //   const item = keys[i]
    //   if (item == slotProps.rowId) {
    //     let goodsId = ''
    //     let arr = Object.keys(this.goodsIdObj)
    //     arr.forEach((ite) => {
    //       if (ite == slotProps.rowId) {
    //         goodsId = this.goodsIdObj[ite].goodsId
    //       }
    //     })
    //     getQuerySpecsNameByGoodsIdC({ goodsId }).then((res) => {
    //       let { success, result } = res
    //       if (success) {
    //         this.$set(this.goodsSkuData, item, result.specsList)
    //       }
    //     })
    //   }
    // }
    // },
    goodsSkuChange(props, value) {
      let arr = Object.keys(this.goodsIdObj)
      if (arr.length) {
        arr.forEach((item) => {
          if (item == props.rowId) {
            this.$set(this.goodsIdObj[item], 'goodsSpecification', value)
          }
        })
      }
    },
    // 获取当前行商品ID及行ID
    goodsIdChange(type, value, row, column, callback, target) {
      let arr = Object.keys(this.goodsIdObj)
      if (type === 'change' && arr.length) {
        arr.forEach((item) => {
          if (item == row.id) {
            this.$set(this.goodsIdObj[item], 'goodsId', value)
            this.$set(this.goodsIdObj[item], 'goodsSpecification', '')
            this.$set(this.goodsIdObj[item], 'unitId', '')
            // 商品变化请求相关联内容
            getQuerySpecsNameByGoodsIdC({ goodsId: value }).then((res) => {
              let { success, result } = res
              if (success) {
                this.$set(this.goodsSkuData, item, result.specsList)
                this.$set(this.storeUnitsData, item, result.unitRelationList)
                this.$set(this.goodsIdObj[item], 'isFales', result.unitId_dictText)
                // console.log(result.unitId_dictText)
              }
            })
          }
        })
      }
      callback()
    },

    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.goodsSkuData = {}
      this.storeUnitsData = {}
      this.goodsIdObj = {}

      if (this.listData && !this.model.storeId) {
        this.model.storeId = this.listData[0].id
        this.model.storeId_dictText = this.listData[0].store_name
      }
      // 请求仓库仓位列表
      if (this.model.storeId) {
        getStockPosition({ id: this.model.storeId }).then((res) => {
          if (!res.success) return
          // 请求成功
          this.handleSuccess(res.result.records)
        })
      }

      // 字段值转换
      this.setModelVal(this.model)

      let fieldval = pick(
        this.model,
        'finalAccountDay',
        'checkoutStatus_dictText',
        'storeId',
        'applicant',
        'supplierId',
        'totalPrice',
        'paymentDay',
        'checkoutTime'
      )
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
      // 加载子表数据

      if (this.model.id) {
        // 申请ID
        this.approvalId = this.model.id
        let params = { id: this.model.id }
        this.requestSubTableData(
          this.url.storeApprovalDetail.list,
          params,
          this.storeApprovalDetailTable,
          this.storeApprovalDetailTableValue
        )
      }
    },
    // 仓位请求成功后的处理
    handleSuccess(result) {
      let optionsArr = []
      result.forEach((item) => {
        optionsArr.push({
          title: item.spaceCode,
          text: item.spaceCode,
          value: item.id,
        })
      })
      // 仓库变化给仓位赋值
      this.$set(this.storeApprovalDetailTable.columns[5], 'options', optionsArr)
    },
    // 获取到子表数据
    storeApprovalDetailTableValue(res) {
      let { result } = res
      let dataSource = []
      if (result) {
        if (Array.isArray(result)) {
          dataSource = result
        } else if (Array.isArray(result.records)) {
          dataSource = result.records
        }
      }

      // 初始化子表数据
      this.childTableInit(dataSource)
    },
    childTableInit(dataSource) {
      dataSource.forEach((item) => {
        this.$set(this.goodsIdObj, item.id, {
          goodsId: item.goodsId,
          goodsSpecification: item.goodsSpecification,
          rowKey: item.id,
          storeNum: item.storeNum,
          unitId: item.storeUnits,
          unitRelation: item.unitRelation,
          totalPrice: item.totalPrice,
          isFales: item.unitId_dictText,
        })
      })
      let arr = Object.keys(this.goodsIdObj)
      // 初始化规格
      this.setGoodsSku(arr)
    },
    setGoodsSku(arr) {
      arr.forEach((item) => {
        getQuerySpecsNameByGoodsIdC({ goodsId: this.goodsIdObj[item].goodsId }).then((res) => {
          let { success, result } = res
          if (success) {
            this.$set(this.goodsSkuData, item, result.specsList)
            this.$set(this.storeUnitsData, item, result.unitRelationList)
          }
        })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      allValues.formValue.storeId = this.storeFormObj.storeId_dictText
      allValues.formValue.supplierId = this.supplierFormObj.supplierId_dictText
      allValues.formValue.applicant = this.applicantFormObj.realname

      let arr = Object.keys(this.goodsIdObj)
      arr.forEach((item) => {
        allValues.tablesValue[0].values.forEach((ite, ind) => {
          if (item == ite.id) {
            allValues.tablesValue[0].values[ind].goodsSpecification = this.goodsIdObj[item].goodsSpecification
            allValues.tablesValue[0].values[ind].unitId = this.goodsIdObj[item].unitId
            allValues.tablesValue[0].values[ind].unitRelation = this.goodsIdObj[item].unitRelation
          }
        })
      })
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        storeApprovalDetailList: allValues.tablesValue[0].values,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    storeCallback(row) {
      this.storeFormObj = row
      this.form.setFieldsValue(pick(row, 'storeId'))
      getStockPosition({ id: row.storeId_dictText }).then((res) => {
        if (!res.success) return
        // 请求成功
        this.handleSuccess(res.result.records)
      })
    },
    supplierCallback(row) {
      this.supplierFormObj = row

      this.form.setFieldsValue(pick(row, 'supplierId'))
    },
    applicantCallback(row) {
      this.applicantFormObj = row
      this.form.setFieldsValue(pick(row, 'applicant'))
    },
    // 将字段值互换
    setModelVal(model) {
      // 字段值互换
      ;[model.storeId, model.storeId_dictText] = [model.storeId_dictText, model.storeId]
      ;[model.supplierId, model.supplierId_dictText] = [model.supplierId_dictText, model.supplierId]
      ;[model.applicant, model.applicant_dictText] = [model.applicant_dictText, model.applicant]
      // 存储初始数据
      this.storeFormObj = {
        storeId: model.storeId,
        storeId_dictText: model.storeId_dictText,
      }
      this.supplierFormObj = {
        supplierId: model.supplierId,
        supplierId_dictText: model.supplierId_dictText,
      }
      this.applicantFormObj = {
        applicant: model.applicant,
        realname: model.applicant_dictText,
      }
    },
  },
}
</script>

<style scoped>
</style>